﻿using System;
using System.Drawing;
using System.Windows.Forms;
using Map_Creator.XNA;
using Point = Microsoft.Xna.Framework.Point;

namespace Map_Creator.MainForm.Controls
{
    public partial class TilesPanels : UserControl
    {
        public GraphicsDeviceControl ActiveTilesControl;

        public TilesPanels()
        {
            InitializeComponent();
            OnTabSelect(TilesPanel,null);
            MapInfo.TileSet.PrimaryTileSetChanged += TileSet_PrimaryTileSetChanged;
        }

        void TileSet_PrimaryTileSetChanged(MapInfo.Map map)
        {
            if (map == null) return;
            var tileSet = MapInfo.Map.SelectedMap.CurrentTileSet;
            if (tileSet == null) return;
            switch (ActiveTilesControl.Name)
            {
                case "TilesPanel":
                    tileSet.SelectionSource = tileSet.Tiles;
                    break;
                case "AnimatedTilesPanel":
                    tileSet.SelectionSource = tileSet.DefinedAnimatedTiles;
                    break;
                case "AutoTilesPanel":
                    tileSet.SelectionSource = tileSet.DefinedAutoTiles;
                    break;
            }
        }

        private void OnSizeChanged(object sender, EventArgs e)
        {
            var senderSize = ((Control) sender).Size;
            // why the hell 8?!?!
            Size = new Size(((Control)sender).Size.Width +
                    SystemInformation.VerticalScrollBarWidth + SystemInformation.Border3DSize.Width * 2 + 8, senderSize.Height);
        }

        private void OnTabSelect(object sender, TabControlEventArgs e)
        {
            ActiveTilesControl = (GraphicsDeviceControl) TabControl.SelectedTab.Controls[0];
            if (MapInfo.Map.SelectedMap == null) return;
            if (MapInfo.Map.SelectedMap.CurrentTileSet == null) return;

            var tileSet = MapInfo.Map.SelectedMap.CurrentTileSet;
            // Reset Selection to 1,1
            tileSet.Selection.OnMouseDown(new Point(1, 1), MouseButtons.Left);
            // Set Source
            switch (ActiveTilesControl.Name)
            {
                case "TilesPanel":
                    tileSet.SelectionSource = tileSet.Tiles;
                    break;
                case "AnimatedTilesPanel":
                    tileSet.SelectionSource = tileSet.DefinedAnimatedTiles;
                    break;
                case "AutoTilesPanel":
                    tileSet.SelectionSource = tileSet.DefinedAutoTiles;
                    break;
            }
        }
    }
}